# from langchain.text_splitter import RecursiveCharacterTextSplitter


# class TextSplitterUtil:

#     def __init__(self):
#         # 定义按词组切割的文本分割器
#         self.separators = ["\n", "\n\n", " ", ""]
#         self.splitter = RecursiveCharacterTextSplitter(
#             chunk_size=50, chunk_overlap=0, separators=self.separators
#         )

#     def split(self, content: str) -> list:
#         """切割文本"""
#         chunks = self.splitter.split_text(content)
#         # 将 chunks 和 content 进行比较，如果有被切割，则在 chunks 中的后面加上被丢弃的切割符号
#         result = []
#         pos = 0
#         for chunk in chunks:
#             end_pos = pos + len(chunk)
#             if end_pos < len(content) and content[end_pos] in self.separators:
#                 chunk += content[end_pos]
#                 end_pos += 1
#             result.append(chunk)
#             pos = end_pos
#         return result


# if __name__ == "__main__":
#     # content = "Helsinki, November 21 (Xinhua) -- The Finnish government announced on the 21st that it will no longer participate in the activities of the Barents Sea Europe Arctic Circle Council after 2025."
#     content = "フィンランド政府は21日、2025年以降同国がバレン支海の欧州-北極圏理事会の活動に参加しないと発表した。"
#     splitter = TextSplitterUtil()
#     print(splitter.split(content))


from docx import Document


class DocxUtils:
    def __init__(self, doc_path):
        self.doc = Document(doc_path)
        self.namespace = {
            "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
            "v": "urn:schemas-microsoft-com:vml",
            "o": "urn:schemas-microsoft-com:office:office",
            "w10": "urn:schemas-microsoft-com:office:word",
        }

    def get_text(self):
        """获取文档中的文本"""
        # 遍历文档中的所有段落
        for para in self.doc.paragraphs:
            print(f"段落文本:{para.text}")

        # 遍历文档中的所有表格
        for table in self.doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    print(f"表格文本:{cell.text}")

        # 遍历文档中的所有文本框
        root = self.doc.element  # 获取文档的 XML 根元素
        for txbxContent in root.findall(".//w:txbxContent", self.namespace):
            for paragraph in txbxContent.findall(".//w:p", self.namespace):
                for text_elem in paragraph.findall(".//w:t", self.namespace):
                    print(f"文本框文本:{text_elem.text}")

        # 遍历文档中的所有艺术字体文本框
        for pict in root.findall(".//w:pict", self.namespace):
            for shape in pict.findall(".//v:shape", self.namespace):
                textpath = shape.find(".//v:textpath", self.namespace)
                if textpath is not None and "string" in textpath.attrib:
                    print(f"艺术字体文本框文本: {textpath.attrib['string']}")

    def replace_text(self):
        # 遍历文档中的所有表格
        for table in self.doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    if cell.text.strip() == "":
                        continue
                    pars = cell.paragraphs
                    for para in pars:
                        for run in para.runs:
                            run.text = "替换后的文本111"

        # 遍历文档中的所有文本框
        root = self.doc.element  # 获取文档的 XML 根元素
        for txbxContent in root.findall(".//w:txbxContent", self.namespace):
            for paragraph in txbxContent.findall(".//w:p", self.namespace):
                for text_elem in paragraph.findall(".//w:t", self.namespace):
                    print(f"文本框文本:{text_elem.text}")

        # 遍历文档中的所有艺术字体文本框
        for pict in root.findall(".//w:pict", self.namespace):
            for shape in pict.findall(".//v:shape", self.namespace):
                textpath = shape.find(".//v:textpath", self.namespace)
                if textpath is not None and "string" in textpath.attrib:
                    print(f"艺术字体文本框文本: {textpath.attrib['string']}")

    def save(self, output_path):
        """保存文档"""
        self.doc.save(output_path)


if __name__ == "__main__":
    doc_path = r"D:\Resources\doc_data\翻译项目\带艺术字体 - 副本.docx"
    doc_util = DocxUtils(doc_path)
    doc_util.get_text()
    doc_util.replace_text()
    doc_util.save(r"D:\临时文件夹\translate_doc\out\output2.docx")
